package com.xxg.renrensearch.apiimpl;

import com.alibaba.fastjson.JSON;
import com.xxg.renrencommon.api.SearchManager;
import com.xxg.renrensearch.dao.Product;
import com.xxg.renrensearch.dao.RenrenShopShop;
import com.xxg.renrensearch.dao.RenrenShopShopDao;
import com.xxg.renrensearch.es.RenRenShopEs;
import com.xxg.renrensearch.repository.ProductRepository;
import com.xxg.renrensearch.repository.RenrenShopShopRepository;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 商品服务接口实现
 *
 * @author xuxiaogang
 * @date 2021-12-02
 */
@DubboService(version = "1.0.0")
@Service
public class SearchManagerImpl implements SearchManager {
    private final ProductRepository productRepository;
    private final RenrenShopShopDao renrenShopShopDao;
    private final RenrenShopShopRepository renrenShopShopRepository;
    private final RenRenShopEs renRenShopEs;

    public SearchManagerImpl(ProductRepository productRepository, RenrenShopShopDao renrenShopShopDao,
                             RenrenShopShopRepository renrenShopShopRepository, RenRenShopEs renRenShopEs) {
        this.productRepository = productRepository;
        this.renrenShopShopDao = renrenShopShopDao;
        this.renrenShopShopRepository = renrenShopShopRepository;
        this.renRenShopEs = renRenShopEs;
    }

    @Override
    public String getSkuInfo(List<String> spuIdPlusSkuId) {
        Iterable<Product> products = productRepository.findAllById(spuIdPlusSkuId);
        return JSON.toJSONString(products);
    }

    @Override
    public String listShopInfo(List<Integer> shopIds) {
        return null;
    }

    @Override
    public void syncShopById(Integer shopId) {
        // 从数据库查询数据
        List<RenrenShopShop> shops = renrenShopShopDao.selectByIds(Collections.singletonList(shopId));
        if (shops.size() != 1) {
            return;
        }
        // 保存到索引库中
        if (!renrenShopShopRepository.existsById(shopId)) {
            renrenShopShopRepository.saveAll(shops);
        }
    }

    @Override
    public String listProductOneSkuUnderSpuBySpuId(List<Integer> spuIds) {
        List<Product> list = renRenShopEs.findCollapseSkusBySpuIds(spuIds, null);
        return JSON.toJSONString(list);
    }
}
